package pl.edu.pjwstk.kor.database.init;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import pl.edu.pjwstk.kor.model.Category;
import pl.edu.pjwstk.kor.model.Customer;
import pl.edu.pjwstk.kor.model.Rank;

public class RankInitalizer extends AbstractDataInitalizer<Rank>{
	private final List<Customer> customers;
	private final List<Category> categories;
	
	public RankInitalizer(List<Customer> customers, List<Category> categories) {
		this.customers = customers;
		this.categories = categories;
	}

	@Override
	public List<Rank> initData() throws Exception {
		List<Rank> result = new ArrayList<Rank>();
		
		for(String line : FileUtils.readLines(new File("src/main/resources/ranks.csv"), "UTF8")) {
			String [] split = line.split(";");
			Rank rank = new Rank();
			rank.setDiscount(getDiscount(split));
			rank.setGroupName(getGroupName(split));
			
			for(Customer customer : customers) {
				if(random.nextBoolean()) {
					rank.getCustomers().add(customer);
					customer.getRanks().add(rank);
				}
			}
			rank.getCategories().add(selectRandom(categories, random));
			
			result.add(rank);
		}
		
		return result;
	}

	private String getGroupName(String[] split) {
		String groupName = split[0];
		if(groupName == null || groupName.trim().isEmpty()) {
			throw new IllegalArgumentException("Group name can not be empty");
		}
		return groupName.trim();
	}

	private Double getDiscount(String[] split) {
		Double discount = Double.parseDouble(split[1]);
		if(discount.doubleValue() >= 1 || discount.doubleValue() < 0) {
			throw new IllegalArgumentException("Discount must be smaller than 1 and bigger than 0");
		}
		return discount;
	}
}
